import React, { PureComponent, Fragment } from 'react';
import { connect } from 'dva';
import { routerRedux } from 'dva/router';
import {
  Row, Col, Card, Form, Input, Select, Icon, Button, Modal, message, Badge, Divider, Tag, Popconfirm,
} from 'antd';
import StandardTable from 'components/StandardTable';
import PageHeaderLayout from '../../layouts/PageHeaderLayout';

import styles from './Goods.less';
import { imgPrex } from '../../utils/constData';

const FormItem = Form.Item;
const { Option } = Select;


@connect(({ goods, loading }) => ({
  goods,
  pagination: goods.pagination,
  loading: loading.models.goods,
}))
@Form.create()
export default class Goods extends PureComponent {
  state = {
    selectedRows: [],
  };

  componentDidMount() {
    const { dispatch } = this.props;
    dispatch({
      type: 'goods/fetchGoodsList',
      payload: { pageNum: 1, pageSize: 10 }
    });
    dispatch({
      type: 'goods/fetchCategoryList',
    });
  }

  handleStandardTableChange = (pagination) => {
    const { dispatch } = this.props;

    const params = {
      pageNum: pagination.current,
      pageSize: pagination.pageSize,
      ...this.props.form.getFieldsValue(),
    };

    dispatch({
      type: 'goods/fetchGoodsList',
      payload: params,
    });
  };

  handleFormReset = () => {
    const { form, dispatch } = this.props;
    form.resetFields();
    const params = {
      pageNum: 1,
      pageSize: this.props.pagination.pageSize ? this.props.pagination.pageSize : 10,
    };
    dispatch({
      type: 'goods/fetchGoodsList',
      payload: params,
    });
  };


  handleSelectRows = rows => {
    this.setState({
      selectedRows: rows,
    });
  };

  handleSearch() {
    const { dispatch, form } = this.props;

    form.validateFields((err, fieldsValue) => {
      if (err) return;

      const values = {
        ...fieldsValue,
        pageNum: 1,
        pageSize: this.props.pagination.pageSize ? this.props.pagination.pageSize : 10,
      };

      dispatch({
        type: 'goods/fetchGoodsList',
        payload: values,
      });
    });
  };



  downOne(goodsId) {
    let recordList = [];
    recordList.push({ goodsId: goodsId })
    this.props.dispatch({
      type: 'goods/downGoodsList',
      payload: { goodsList: recordList },
      callback: () => this.callback()
    });
  }

  upOne(goodsId) {
    let recordList = [];
    recordList.push({ goodsId: goodsId })
    this.props.dispatch({
      type: 'goods/upGoodsList',
      payload: { goodsList: recordList },
      callback: () => this.callback()
    });
  }

  _changeGoodsStatus(type) {
    let list = this.state.selectedRows;
    if (list && list.length > 0) {
      let recordList = [];
      for (let i in list) {
        let one = { goodsId: list[i].goodsId }
        recordList.push(one)
      }

      if (type == "up") {  //上架
        if (recordList) {
          this.props.dispatch({
            type: 'goods/upGoodsList',
            payload: { goodsList: recordList },
            callback: () => this.callback()
          });
        }
      } else if (type == "down") {
        if (recordList) {
          this.props.dispatch({
            type: 'goods/downGoodsList',
            payload: { goodsList: recordList },
            callback: () => this.callback()
          });
        }
      } else if (type == "delete") {
        if (recordList) {
          this.props.dispatch({
            type: 'goods/delGoodsList',
            payload: { goodsList: recordList },
            callback: () => this.callback()
          });
        }
      }
    } else {
      message.error('请选择内容')
    }
  }

  callback() {
    this.handleSearch()
  }

  renderAdvancedForm() {
    const { form } = this.props;
    const { getFieldDecorator } = form;
    return (
      <Form layout="inline">
        <Row gutter={{ md: 8, lg: 24, xl: 48 }}>
          <Col md={8} sm={24}>
            <FormItem label="商品名称">
              {getFieldDecorator('goodsName')(<Input placeholder="请输入" />)}
            </FormItem>
          </Col>
          <Col md={8} sm={24}>
            <FormItem label="类目">
              {getFieldDecorator('catId', { initialValue: 'undefined' })(
                <Select style={{ width: '100%' }}>
                  <Option value="undefined">全部</Option>
                  {(this.props.goods.categoryList && this.props.goods.categoryList.length > 0) && this.props.goods.categoryList.map((item, i) => <Option key={i} value={'' + item.catId}>{item.catName}</Option>)}
                </Select>
              )}
            </FormItem>
          </Col>
          <Col md={8} sm={24}>
            <FormItem label="状态">
              {getFieldDecorator('goodsSts', { initialValue: 'undefined' })(
                <Select style={{ width: '100%' }}>
                  <Option value="undefined">全部</Option>
                  {/* <Option value="0">已发布</Option> */}
                  <Option value="1">已上架</Option>
                  <Option value="2">已下架</Option>
                </Select>
              )}
            </FormItem>
          </Col>
        </Row>

        <div style={{ overflow: 'hidden' }}>
          <span style={{ float: 'right', marginBottom: 24 }}>
            <Button type="primary" htmlType="submit" onClick={() => this.handleSearch()}>
              查询
            </Button>
            <Button style={{ marginLeft: 8 }} onClick={this.handleFormReset}>
              重置
            </Button>
          </span>
        </div>
      </Form>
    );
  }


  render() {
    const { goods, loading, } = this.props;

    const tableData = {}
    tableData['list'] = goods.goodsList;
    tableData['pagination'] = goods.pagination;

    const { selectedRows, modalVisible } = this.state;

    const columns = [
      {
        title: '商品Id',
        dataIndex: 'goodsId',
        key: 'goodsId',
      },
      {
        title: '封面',
        dataIndex: 'goodsImg',
        key: 'goodsImg',
        render(text, record) {
          return <img src={imgPrex + record.goodsImg} alt={record.title} style={{ width: 30, height: 30 }} />;
        },
      },
      {
        title: '商品名称',
        dataIndex: 'goodsName',
        key: 'goodsName',
      },
      {
        title: '类目',
        dataIndex: 'catName',
        key: 'catName',
      },
      {
        title: '价格',
        dataIndex: 'discountPrice',
        key: 'discountPrice',
      },
      {
        title: '状态',
        dataIndex: 'goodsSts',
        key: 'goodsSts',
        render(val) {
          return val == "0" ? "已发布" : val == "1" ? <span >上架</span> : val == "2" ? <span style={{ color: 'red' }}>下架</span> : null
        },
      },
      {
        title: '权重',
        dataIndex: 'weight',
        key: 'weight',
      },
      {
        title: '操作',
        key: '操作',
        render: (text, record) => (
          <Fragment>
            <a onClick={() => this.props.dispatch(routerRedux.push({ pathname: '/points/editGoods/' + record.goodsId }))}>编辑</a>
            <Divider type="vertical" />
            {record.goodsSts == "1" ? <a onClick={() => this.downOne(record.goodsId)}> <span style={{ color: '#8E8E8E' }}>下架</span></a> : record.goodsSts == "2" ? <a onClick={() => this.upOne(record.goodsId)}>上架</a> : null}
          </Fragment>
        ),
      },
    ];

    return (
      <PageHeaderLayout title="">
        <Card bordered={false}>
          <div className={styles.tableList}>
            <div className={styles.tableListForm}>{this.renderAdvancedForm()}</div>
            <div className={styles.tableListOperator}>
              <Button icon="plus" type="primary" onClick={() => this.props.dispatch(routerRedux.push({ pathname: '/points/editGoods/new' }))}>
                新建
              </Button>
              {selectedRows.length > 0 && (
                <span>
                  <Popconfirm title={"你确定要上架选择的" + this.state.selectedRows.length + "个选项吗?"} placement="bottom" onConfirm={() => this._changeGoodsStatus("up")} onCancel={() => { }} okText="确定" cancelText="取消">
                    <Button type="primary" icon="upload" >
                      上架
                  </Button>
                  </Popconfirm>
                  <Popconfirm title={"你确定要下架选择的" + this.state.selectedRows.length + "个选项吗?"} placement="bottom" onConfirm={() => this._changeGoodsStatus("down")} onCancel={() => { }} okText="确定" cancelText="取消">
                    <Button type="primary" icon="download">
                      下架
                  </Button>
                  </Popconfirm>
                  <Popconfirm title={"你确定要上架选择的" + this.state.selectedRows.length + "个选项吗?"} placement="bottom" onConfirm={() => this._changeGoodsStatus("delete")} onCancel={() => { }} okText="确定" cancelText="取消">
                    <Button type="danger" icon="delete">
                      删除
                  </Button>
                  </Popconfirm>

                </span>
              )}
            </div>
            <StandardTable
              selectedRows={selectedRows}
              loading={loading}
              data={tableData}
              columns={columns}
              onSelectRow={this.handleSelectRows}
              onChange={this.handleStandardTableChange}
              rowKey="goodsId"
            />
          </div>
        </Card>
      </PageHeaderLayout>
    );
  }
}
